package com.ruoyi.predict.utils;

import com.ruoyi.predict.aiDomain.JobRecommendation;
import com.ruoyi.predict.aiDomain.JobRecommendationResponse;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JobRecommendationParser2 {

    /**
     * 解析AI返回的文本为结构化数据（修复岗位名错乱问题）
     */
    public static JobRecommendationResponse parse(String aiResponseText) {
        JobRecommendationResponse response = new JobRecommendationResponse();
        List<JobRecommendation> recommendations = new ArrayList<>();

        if (!StringUtils.hasText(aiResponseText)) {
            response.setRecommendations(recommendations);
            return response;
        }

        // 1. 预处理：移除冗余内容
        String cleanedText = preprocessText(aiResponseText);

        // 2. 尝试多策略解析
        recommendations = parseWithStrictPattern(cleanedText);
        if (!recommendations.isEmpty()) {
            // 修复可能的岗位名错乱问题
            fixJobNameIssues(recommendations);
            response.setRecommendations(recommendations);
            return response;
        }

        recommendations = parseWithLenientPattern(cleanedText);
        if (!recommendations.isEmpty()) {
            fixJobNameIssues(recommendations);
            response.setRecommendations(recommendations);
            return response;
        }

        recommendations = parseWithKeywords(cleanedText);
        fixJobNameIssues(recommendations);
        response.setRecommendations(recommendations);
        return response;
    }

    /**
     * 核心修复：当jobName无效时，从reason中提取真实岗位名
     */
    private static void fixJobNameIssues(List<JobRecommendation> jobs) {
        for (JobRecommendation job : jobs) {
            // 判断当前jobName是否无效（如“位名称”“未知岗位”等）
            if (isInvalidJobName(job.getJobName())) {
                // 从reason中提取岗位名（匹配“XXX 推荐理由：”格式）
                String realJobName = extractJobNameFromReason(job.getReason());
                if (StringUtils.hasText(realJobName)) {
                    job.setJobName(realJobName);
                    // 同时清理reason中的岗位名前缀
                    job.setReason(cleanReasonAfterJobName(job.getReason(), realJobName));
                }
            }
        }
    }

    /**
     * 判断岗位名是否无效
     */
    private static boolean isInvalidJobName(String jobName) {
        if (!StringUtils.hasText(jobName)) return true;
        // 无效关键词列表：可根据实际情况扩展
        String[] invalidKeywords = {"位名称", "未知岗位", "岗位名", "岗位名称"};
        for (String keyword : invalidKeywords) {
            if (jobName.contains(keyword)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 从reason中提取真实岗位名（匹配“岗位名 推荐理由：”格式）
     */
    private static String extractJobNameFromReason(String reason) {
        if (!StringUtils.hasText(reason)) return "";
        // 正则：匹配“XXX 推荐理由：”中的XXX（岗位名）
        Pattern pattern = Pattern.compile("^(.*?)\\s*推荐理由：", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(reason);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        // 备选：如果没有“推荐理由”关键词，取reason开头的有意义内容
        return reason.split("\\s+")[0].trim(); // 取第一个空格前的内容
    }

    /**
     * 清理reason：移除开头的岗位名前缀
     */
    private static String cleanReasonAfterJobName(String reason, String jobName) {
        if (!StringUtils.hasText(reason) || !StringUtils.hasText(jobName)) {
            return reason;
        }
        // 移除reason中开头的岗位名和“推荐理由：”前缀
        return reason.replaceFirst("^" + Pattern.quote(jobName) + "\\s*推荐理由：?", "").trim();
    }

    // ------------------------------ 以下是原有辅助方法（保持不变） ------------------------------
    private static String preprocessText(String text) {
        if (text == null) return "";
        text = text.replaceAll("\\s*toolExecutionRequests\\s*=\\s*null\\s*", "");
        text = text.replaceAll("[\"{}]", "");
        text = text.replaceAll("\\s+", " ").trim();
        return text;
    }

    private static List<JobRecommendation> parseWithStrictPattern(String text) {
        List<JobRecommendation> list = new ArrayList<>();
        Pattern pattern = Pattern.compile(
                "(\\d+)\\.\\s*岗位名：(.*?)\\s*推荐理由：(.*?)(?=\\s+\\d+\\.|$)",
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE
        );
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            JobRecommendation job = new JobRecommendation();
            job.setIndex(Integer.parseInt(matcher.group(1).trim()));
            job.setJobName(matcher.group(2).trim());
            job.setReason(matcher.group(3).trim().replaceAll("\\s+", " "));
            list.add(job);
        }
        return list;
    }

    private static List<JobRecommendation> parseWithLenientPattern(String text) {
        List<JobRecommendation> list = new ArrayList<>();
        Pattern pattern = Pattern.compile(
                "(\\d+)\\.?\\s*[岗位名:：](.*?)[推荐理由:：](.*?)(?=\\s+\\d+\\.?|$)",
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE
        );
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            JobRecommendation job = new JobRecommendation();
            job.setIndex(Integer.parseInt(matcher.group(1).trim()));
            String jobName = matcher.group(2).trim().replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "");
            job.setJobName(jobName);
            job.setReason(matcher.group(3).trim().replaceAll("\\s+", " "));
            list.add(job);
        }
        return list;
    }

    private static List<JobRecommendation> parseWithKeywords(String text) {
        List<JobRecommendation> list = new ArrayList<>();
        String[] parts = text.split("\\s+\\d+\\.\\s*");
        int index = 1;
        for (String part : parts) {
            if (index > 3) break;
            if (!StringUtils.hasText(part)) continue;
            JobRecommendation job = new JobRecommendation();
            job.setIndex(index);
            String jobName = extractPart(part, "岗位", "理由");
            String reason = extractPart(part, "理由", null);
            job.setJobName(StringUtils.hasText(jobName) ? jobName : "未知岗位" + index);
            job.setReason(StringUtils.hasText(reason) ? reason : "无推荐理由");
            list.add(job);
            index++;
        }
        return list;
    }

    private static String extractPart(String text, String startKey, String endKey) {
        int start = text.indexOf(startKey);
        if (start == -1) start = 0;
        else start += startKey.length();
        int end = text.length();
        if (endKey != null && text.indexOf(endKey) > start) {
            end = text.indexOf(endKey);
        }
        return text.substring(start, end).trim().replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5,.，。]", "");
    }
}